//
//  BluBusiness.m
//  KangarooDoctor
//
//  Created by 廖罡 on 2024/2/1.
//

#import "BluBusiness.h"
#import "BLU.h"
#import "../PackParse/PackParse.h"
#import "Pack.h"


NSString* getErr(int i)
{
    if (i > 7) {
        return @"no this err";
    }
    
    NSArray<NSString*> *table = @[
        @"logic err",
        @"传感器震荡异常",
        @"检测不到足够的心跳或算不出血压",
        @"测量结果异常",
        @"袖带过松或漏气",
        @"气管被堵住",//5
        @"测量时压力波动大",
        @"压力超过上限",
    ];
    
    return table[i];
}


@interface BluBusiness ()
<BLUP>
@property (nonatomic, strong) BLU *blu;
@property (nonatomic, strong) NSString * uuid;
@end

@implementation BluBusiness
+(instancetype)shared
{
    static BluBusiness *s = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        s = [[BluBusiness alloc] init];
    });
    return s;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.blu = [BLU shared];
        self.blu.delegate = self;
    }
    return self;
}

- (CBPeripheralState) getBluStatus {
    
    NSLog(@"getBluStatus: %@  %@ %d", self.uuid, self.blu.peripheral.identifier, self.blu.peripheral.state);
    if( self.uuid != NULL && ![self.uuid isEqualToString:self.blu.peripheral.identifier.UUIDString] ){
        return 0;
    }
    return self.blu.peripheral.state;
}

- ( NSString * ) getBluDeviceId {
    return self.blu.peripheral.identifier.UUIDString;
}


-(void)startWithPageName: (NSString *) name uuid:(nonnull NSString *)uuid
{
    self.uuid = uuid;
    [self.blu startWithPageName:name uuid:uuid];
}

-(void)stop
{
    [self.blu stop];
}

-(void)bluDidDisconnect
{
    [self.delegate bluDidDisconnect];
}

-(void)bluStatusDidChange:(NSString*)msg
{
    [self.delegate bluDidReceiveMsg:msg];
}


- ( void ) getDeviceList:(NSArray *) list {
    NSLog(@"2222222  %@", self.delegate);
    [self.delegate getDeviceList: list];
}


//处理错误数据
- ( void ) startErrorHandle:(const BYTE*)buf len:(int)len {
        NSInteger value = buf[3] & 0xff;
        NSString * status = @"";
        switch (value){
          case 1:
                status= @"人体心跳信号太小或者压力突降";
            break;
          case 2:
                status= @"杂讯干扰";
            break;
          case 3:
                status= @"充气时间过长";
            break;
          case 5:
                status= @"测得结果异常";
            break;
          case 11:
                status= @"电源低电压";
            break;
          default:
                status= @"测量发生异常，请重新测量";
          break;
        }
    [self.delegate bluDidReceiveCalcFailResult:status];
}

//处理成功数据
- ( void ) startSuccessHandle:(const BYTE*)buf len:(int)len {
    NSInteger highPress = buf[3];
    NSInteger lowPress = buf[4];
    NSInteger pulse = buf[5];
    NSLog(@"startSuccessHandle~~~  highPress: %ld lowPress:%ld", highPress &0xff, lowPress & 0xff);
    
    [self.delegate bluDidReceiveCalcResult:highPress lowPress:lowPress heartBeat:pulse];
}

//处理传输数据
- ( void ) startProccingHandle:(const BYTE*)buf len:(int)len {
    
    NSInteger highPress = buf[3];
    NSInteger lowPress = buf[4];
    NSInteger pulse = buf[5];
    NSLog(@"startProccingHandle~~~  highPress: %ld lowPress:%ld", highPress &0xff, lowPress & 0xff);
    [self.delegate bluDidReceiveRealTimeReport:highPress lowPress:lowPress heartBeat:pulse];
}


/**
   读取到数据
 **/
-(void) didReadData:(const BYTE*)buf len:(int)len
{
    struct Wrap *wrap = malloc(sizeof(struct Wrap));
    bzero(wrap, sizeof(struct Wrap));

    
    //判断是不是连接上蓝牙
    bool isConnectStart =  [self isBpDeviceConnect:buf len:len];
    
    if( isConnectStart ){
        [self.blu writeStartData];
        return;
    }
    
    
    //是否开始测量
    bool isStartMeasure = [self isBpDeviceStartMeasure:buf len:len];
    if( isStartMeasure ){
        return;
    }
  
    
    NSLog(@"buf[2]:  %d", buf[2] & 0xff);
    
    switch ( buf[2] & 0xff ) {
        case 253:
            //测量出现异常的指令。
            [self startErrorHandle:buf len:len];
            break;
        case 251:
            //测量中数据传输指令。
            [self startProccingHandle:buf len:len];
            break;
        case 252:
            //测量完成
            [self startSuccessHandle:buf len:len];
            break;
        default:
            break;
    }
}

- ( bool ) isBpDeviceStartMeasure:(const BYTE*)buf len:(int)len  {

    NSLog(@"isBpDeviceStartMeasure: %ld", len);
    bool isStartMeasure = TRUE;
    if( len != 6 ){
        return FALSE;
    }
    
    
//    fd-fd-fb-00-00-0d-0a-
    
    int value1 = buf[0] & 0xff;
    int value2 = buf[1] & 0xff;
    int value3 = buf[2] & 0xff;
    int value4 = buf[3] & 0xff;
    int value5 = buf[4] & 0xff;
    int value6 = buf[5] & 0xff;
    if( value1 != 253 ){
        isStartMeasure = FALSE;
    }
    if( value2 != 253 ){
        isStartMeasure = FALSE;
    }
    if( value1 != 250 ){
        isStartMeasure = FALSE;
    }
    if( value1 != 6 ){
        isStartMeasure = FALSE;
    }
    if( value1 != 11 ){
        isStartMeasure = FALSE;
    }
    if( value1 != 10 ){
        isStartMeasure = FALSE;
    }
    return isStartMeasure;
}

- ( bool ) isBpDeviceConnect:(const BYTE*)buf len:(int)len {
    
    
    bool isBoDeviceStart = TRUE;

    while ( len-- ) {
        printf("%02x-", *buf & 0xff);
        buf++;
    }
    printf("\n\n\n");
    
    
    if( len != 9 ){
        return FALSE;
    }
    
//    ff ff ff fd ff ff ff fd ff ff ff fa 06 0d 0a
    
    
//    ff ff ff fd ff ff ff fd ff ff ff a4 01 00 01 00 0d 0a
    int value1 = buf[0] & 0xff;
    int value2 = buf[1] & 0xff;
    int value3 = buf[2] & 0xff;
    int value4 = buf[3] & 0xff;
    int value5 = buf[4] & 0xff;
    int value6 = buf[5] & 0xff;
    int value7 = buf[6] & 0xff;
    int value8 = buf[7] & 0xff;
    int value9 = buf[8] & 0xff;
    NSLog(@"value1: %d, value2: %d, value3: %d, value4: %d, value5: %d, value6: %d, value7: %d, value8: %d, value9: %d", value1, value2, value3, value4, value5, value6, value7, value8, value9);
    
    if( value1 != 253 ){
        isBoDeviceStart = FALSE;
    }
    if( value2 != 253 ){
        isBoDeviceStart = FALSE;
    }
    if( value3 != 164 ){
        isBoDeviceStart = FALSE;
    }
    if( value4 != 1 ){
        isBoDeviceStart = FALSE;
    }
    if( value5 != 0 ){
        isBoDeviceStart = FALSE;
    }
    if( value6 != 1 ){
        isBoDeviceStart = FALSE;
    }
    if( value7 != 0 ){
        isBoDeviceStart = FALSE;
    }
    if( value8 != 13 ){
        isBoDeviceStart = FALSE;
    }
    if( value9 != 10 ){
        isBoDeviceStart = FALSE;
    }
    
    return TRUE;

}

- ( void ) startMessare {
    [self.delegate startMessare];
}

- (void)connectPeripheral:(CBPeripheral *)peripheral{
    [self.blu connectPeripheral: peripheral];
}

@end


